#! /bin/bash
# This is written just for those xfce tasks... Political incorrect.
# This script tries to convert Archlinux PKGBUILD things into autobuild defines. It simply does the copy and paste job.

# Date format.
LANG=C

##General Functions, move to abbs libs.
# fundump funname filename
fundump(){ declare -f "$1" | head -n+1 | tail -n+2 | sed -re 's/^    //g' >> "$2"; }
# funhere funname
funhere(){ declare -F "$1" &>/dev/null; }
# getfile file
getfile(){
    case "$1" in
        http://*|ftp://*)
            wget -nv "$1";;
        git://*)
            git clone --depth 1 "$1";;
        *://*)
            warn "So what's \`$1'?"; return 1;;
        *)
            echo "Local file $1."
            cp -l "$orig/$1" .
    esac
    set -- "$(basename $1)"
    # Actually we can have everything done with 7z.
    case "$1" in
        *.tar*|*.zip|*.rar|*.7z)
            7z x "$1" # tar -xf "$1";; unzip "$1";; unrar "$1";;
    esac
}
##Local Funcs
die(){ echo "FATAL: $1" >&2; exit ${2-1}; }
info(){ echo "INFO: $1"; }
warn(){ echo "WARN: $1" >&2; }
# HELP
print_help() {
    echo -e "\e[1mUsage:\e[0m pkg2ab [PKGBUILD-PATH] \e[2m[foo.install]
    \e[1mVaribles that affect pkg2ab:\e[0m
    ArchPatch = [ 0 | 1 ] \t\t Set if pkg2ab should include PKGBUILD prepare() to autobuild patch.
    XtraPatch = <first>\\\n<then>... \t Extra things to add to autobuild patch."
    exit ${2-0}
}
# Defaults
export ArchPatch=${ArchPatch=1}

# Startup & Loading
[ "$1" == --help ] && print_help

[ -z "$1" ] && set -- $PWD/PKGBUILD
. "$1" || die "Failed to load PKGBUILD $1."

[ -z "$2" ] && set -- "$1" ${pkgname}.install
. "$2" || echo "Never mind."

temp=/tmp/mkab-$(date +%s)
orig="$PWD"
mkdir -p $temp
cd $temp

info "Fetching files as defined in PKGBUILD."
for file in ${source[@]}; do getfile "$file"; done

info "Creating ab files."

mkdir -p autobuild.gen/patches
echo "# Generated by pkg2ab on $(date)" > autobuild.gen/patch
if [ "$ArchPatch" == 1 ]; then
    cp *.{patch/diff} autobuild.gen/patches
    fundump prepare autobuild.gen/patch
fi
echo -e "$XTraPatch" >> autobuild.gen/patch 

# TODO: verspec member translation to ab syntax.
cat > autobuild.gen/defines << _end_of_abdef
# Generated by pkg2ab on $(date)
PKGNAME=$pkgname
PKGVER=$pkgver
PKGDES="$pkgdesc"
PKGDEP="${depends[@]}"
BUILDDEP="${makedepends[@]}"
_end_of_abdef

funhere post_install && fundump post_install autobuild.gen/postinst
# TODO post_remove, ...

echo -e "\e[1mComplete! \nView Results in ${temp}.\e[31m Always check the files manually before you run autobuild.\e[0m"
